
// https://leetcode.cn/problems/unique-paths-iii/description/

class Solution
{
    int cnt = 0;
    int sum = 0;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int sx, sy;
    int m, n;

public:
    int uniquePathsIII(vector<vector<int>>& grid)
    {
        m = grid.size();
        n = grid[0].size();
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (grid[i][j] != -1)
                {
                    ++sum;
                    if (grid[i][j] == 1)
                    {
                        sx = i;
                        sy = j;
                    }
                }
            }
        }
        dfs(grid, sx, sy, 1);
        return cnt;
    }

    void dfs(vector<vector<int>>& grid, int i, int j, int path_size)
    {
        if (grid[i][j] == 2)
        {
            if (path_size == sum)
                ++cnt;
            return;
        }

        grid[i][j] = -1;

        for (int k = 0; k < 4; ++k)
        {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] != -1)
                dfs(grid, x, y, path_size + 1);
        }

        grid[i][j] = 0;
    }
};